package com.jt.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.jt.vo.ImageVO;

@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {
	
	//设定本地存储的根目录
	@Value("${image.localPath}")
	private String localPath;	// = "E:/JT_IMAGE/";
	@Value("${image.urlPath}")
	private String urlPath;
	
	/**
	 * 1.图片校验  jpg|png|gif
	 * 2.是否为恶意程序   木马.exe.jpg  宽度:      高度:
	 * 3.分目录储存.  目的:控制目录中图片的数量.
	 * 4.防止重名.
	 * 
	 * 解决方案:
	 * 	1.根据if判断,判断后缀是否包含指定的名称?  正则表达式
	 * 	2.将数据把它填充到图片对象中.之后利用工具API获取宽度和高度.?
	 * 	3. 利用hash方式进行目录存储,  利用时间进行目录存储.?
	 * 	4.随机数, UUID方式?
	 */
	@Override
	public ImageVO fileUpload(MultipartFile uploadFile) {
		//1.需要获取图片的名称    abc.jpg
		String fileName = uploadFile.getOriginalFilename();
		//将数据转化为小写字母.
		fileName = fileName.toLowerCase();
		//2.利用正则表达式 判断是否为图片
		if(!fileName.matches("^.+\\.(jpg|png|git)$")){
			//表示不是图片信息
			return ImageVO.fail();
		}
		
		//3.判断图片是否为恶意程序
		try {
			BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
			int width = bufferedImage.getWidth();	//固有属性
			int height = bufferedImage.getHeight();
			
			if(width ==0 || height ==0) {
				
				return ImageVO.fail();
			}
			
			//4.分目录存储. E:/JT_IMAGE/yyyy/MM/dd/
			String dateDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
			String localDir = localPath + dateDir;
			File file = new File(localDir);
			if(!file.exists()) {
				//如果目录不存在,则创建目录
				file.mkdirs();
			}
			
			//5.为了防止文件重名,指定文件名称 uuid.jpg
			String uuid = UUID.randomUUID().toString().replace("-", "");
			//abc.jpg
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			String realFileName = uuid+fileType;
			
			//6.实现文件上传
			String realFilePath = localDir + realFileName;
			File realFile = new File(realFilePath);
			uploadFile.transferTo(realFile);
			
			//设定虚拟地址http://image.jt.com/yyyy/MM/dd/uuid.jpg
			String url = urlPath+dateDir+realFileName;
			//String url = "https://img14.360buyimg.com/n0/jfs/t1/95589/40/14004/140230/5e5f7c6aE024b279a/c80ab618198398fb.jpg";
			return ImageVO.success(url, width, height);
			
		} catch (IOException e) {
			
			e.printStackTrace();
			return ImageVO.fail();
		}
	}
}
